package com.my.javaweb;

import javax.jws.WebService;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/*******
 * ServletConfig配置类
 * getInitParameter获取参数值方法
 * ServletContext上下文类
 *
 * */
@WebServlet(name = "servlet2" ,urlPatterns = "/ser2")
public class ServletDemo02 extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        System.out.println("------------------init-----------------");
        //getServletName(); 获取servlet的名称，也就是我们在web.xml中配置的servlet-name
        String name = config.getServletName();
        //getInitParameter(String);获取在servlet中初始化参数的值。这里注意与全局初始化参数的区分。这个获取的只是在该servlet下的初始化参数
        String para1 = config.getInitParameter("sd3");//获取前缀
        String para2 = config.getInitParameter("sd4");//获取后缀
        System.out.println("servlet的name："+name+" servletd的初始参数:"+para1+"  "+para2);
        //getServletContext(); 获取上下文变量
        ServletContext context = config.getServletContext();
        String param = context.getInitParameter("param1");
        System.out.println("访问全局的初始化参数:"+param);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        resp.getWriter().write("this is from doGet.");
        System.out.println("------------------doGet-----------------");
        ServletConfig config = this.getServletConfig();// 拿到init方法中的ServletConfig对象

        // 获取配置信息里的初始化参数
        String sname = config.getServletName();
        System.out.println("servlet名字" + sname );

        //getInitParameterNames(); 注意返回的是枚举类型
        //获取在Servlet中所有初始化参数的名字，也就是key值，可以通过key值，来找到各个初始化参数的value值。
        Enumeration enumration = config.getInitParameterNames();
        while (enumration.hasMoreElements()) {
            String name = (String)enumration.nextElement();
            String value = config.getInitParameter(name);
            System.out.println(name+":"+value);
        }
        ServletContext context = config.getServletContext();
        String address = context.getInitParameter("param2");
        System.out.println("Context:"+address);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);

    }

}
